<?php

namespace app\api\controller;

use ba\Tree;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use EasyWeChat\OfficialAccount\Application as wechatApplication;

class Wechat extends Frontend
{
    protected array $noNeedLogin = ['index'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function index()
    {
        $config = [
            'app_id' => 'wx195ade7461459a9b',
            'secret' => '0a97e479092be8788c5a59dfed9b3dec',
            //'token' => 'easywechat',
            'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
        
            /**
             * OAuth 配置
             *
             * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
             * redirect_url：OAuth授权完成后的回调页地址
             */
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'redirect_url' => '/examples/oauth_callback.php',
            ],
        
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
               
            ],
        ];
        $app = new wechatApplication($config);
        $accessToken = $app->getAccessToken();
        $accessToken->getStableAccessToken(); // string
        $api = $app->getClient();
        $response = $api->get('/cgi-bin/user/get', [
            'next_openid' => 'o-E4as38WihKbux0J4VqDh2CulzQ',
        ]);
        $result = $response->toArray()['data']['openid'];
        $openid = [];
        foreach ($result as $key => $value) {
            $openid[] = ['wechat_openid' => $value];
        }
        Db::name('MpWechat')->insertAll($openid);
        dump($response->toArray());
    }
}